﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace VisualFaml
{
    public partial class DebugWindow : Form
    {
        public DebugWindow()
        {
            InitializeComponent();            
        }

        private DebugWindowListener debug;

        public string SaveTo
        {
            set
            {
                toolLogSaveTo.Text = "Los is saving to " + value;
            }
        }

        public DebugWindowListener Listener
        {
            get
            {
                return debug;
            }
            set
            {
                this.textBox1.Clear();
                debug = value;
                SetLines(debug.Messages);
                debug.NewMessage += new EventHandler(debug_NewMessage);
            }
        }

        void debug_NewMessage(object sender, EventArgs e)
        {
            SetLines(debug.Messages);
        }

        void SetLines(string[] lines)
        {
            if (this.textBox1.InvokeRequired)
            {
                this.textBox1.Invoke(new SetLinesDel(SetLines), lines);
            }
            else
            {
                this.textBox1.Lines = lines;
            }
        }

        private delegate void SetLinesDel(string[] lines);


        private void DebugWindow_Load(object sender, EventArgs e)
        {

        }
    }

    public class DebugWindowListener : TraceListener
    {
        public List<string> entries;

        public DebugWindowListener()
        {
            entries = new List<string>();
        }

        private string[] Parse(string message)
        {
            string[] lines = message.Split('\n');
            lines[0] = DateTime.Now.ToString() + ": " + lines[0];
            return lines;
        }

        public override void Write(string message)
        {
            entries.AddRange(Parse(message));
            if (NewMessage != null)
                NewMessage(this, new EventArgs());
        }

        public override void WriteLine(string message)
        {
            entries.AddRange(Parse(message));
            if (NewMessage != null)
                NewMessage(this, new EventArgs());
        }

        public event EventHandler NewMessage;

        public string[] Messages
        {
            get { return entries.ToArray(); }
        }
    }
}
